package com.sjt.mylibrary.utils.net;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.callback.AbsCallback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;

public abstract  class JsonCallback <T> extends AbsCallback<T> {

    private Type type;
    private Class<T> clazz;

    public JsonCallback() {
    }

    public JsonCallback(Type type) {
        this.type = type;
    }

    public JsonCallback(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        //不同的业务，这里的代码逻辑不一样，需要对应修改
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
        //这里得到第二层泛型的所有的类型
        Type type = params[0];

        if(!(type instanceof ParameterizedType)) throw new IllegalStateException("没有填写泛型参数");
        //这里得到第二层数据的真实类型：ComRespons
        Type rawType = ((ParameterizedType)type).getRawType();
        //这里得到第二层数据的泛型的真实类型:modelbean
        Type typeArgument = ((ParameterizedType)type).getActualTypeArguments()[0];

        ResponseBody body = response.body();
        if(body == null) return null;
        Gson gson = new Gson();
        JsonReader jsonReader = new JsonReader(body.charStream());
        if(rawType!= ComRespons.class){
            T data = gson.fromJson(jsonReader,type);
            response.close();
            return data;
        }else{
            if(typeArgument == Void.class){
                //无数据类型，new DialogCallback<ComRespons<Void>>()以这种形式传递的泛型
                SimpleResponse simpleResponse = gson.fromJson(jsonReader,SimpleResponse.class);
                response.close();
                //noinspection unchecked
                String code = simpleResponse.response;
                //code == "000000"时代表成功
                if("000000".equals(code)){
                    //noinspection unchecked
                    return (T) simpleResponse;
                }else if("40001".equals(code)){
                    throw new IllegalStateException("40001"+simpleResponse.message);
                }else{
                    throw new IllegalStateException("错误代码："+code+",错误信息："+simpleResponse.message);
                }
            }else{
                ComRespons comRespons = gson.fromJson(jsonReader,type);
                response.close();
                String code = comRespons.response;
                //code == "000000"时代表成功
                if("000000".equals(code)){
                    //noinspection unchecked
                    return (T) comRespons;
                }else if("40001".equals(code)){
                    throw new IllegalStateException("40001"+comRespons.message);
                }else{
                    throw new IllegalStateException("错误代码："+code+",错误信息："+comRespons.message);
                }
            }
        }
    }
}
